#! python
#! coding: utf-8

__author__ = 'Anton Vakhrushev'

import os
import wx
from lib.models import album
from lib.models import yafotki
from lib.models import cachedb
from lib.controllers import progressctr
from lib.extra import utils
from lib.forms import overviewfrm
from lib.forms import authfrm
from lib.forms import syncfrm
from lib.forms import singleviewfrm


PROGRAM_NAME = u'Phoebe'
SETTINGS_FILE = u'settings.json'

DEFAULT_USER_SETTINGS = {
    'pagewidth': 804,
    'imageborder': 2,
    'group_temp': '<center>{{rows}}</center>\n',
    'row_temp': '<a href="{{1200:href}}"><img src="{{*:href}}" width="{{*:w}}" height="{{*:h}}"/></a>',
    'href_temp': '{{1000:href}}.jpg\n',
    'albums': {},
}


class OverviewController(object):
    def __init__(self, app):
        self.app = app              # экземпляр приложения
        """@type : wx.App"""
        self.form = None            # форма представления данных
        """@type : wx.OverviewForm"""
        self.app_settings = {}      # настройки приложения
        """@type : dict"""
        self.user_name = u''        # имя текущего пользователя
        """@type : unicode"""
        self.user_settings = {}     # настройки пользователя
        """@type : dict"""
        self.service_album = None   # сервисный альбом
        """@type : album.ServiceAlbum"""

        self.init()

    def album_settings(self, alb):
        syncfrm.SyncSettingsDialog(alb, self.form).Run()
        self.save_album_settings(alb)
        self.form.UpdateAlbumView(alb)

    def copy_photos(self, imglist, cols=1):
        """
        Place photos
        @type imglist: list of photo.MatchedPhoto
        """
        stripeWidth = self.user_settings['pagewidth']
        stripeBorder = self.user_settings['imageborder']
        stripeHeight = stripeWidth - 2 * stripeBorder
        group_temp = self.user_settings['group_temp']
        row_temp = self.user_settings['row_temp']
        rows = len(imglist) / cols + bool(len(imglist) % cols)
        text = ''

        for i in xrange(rows):
            row = imglist[i * cols : (i + 1) * cols]
            dims = utils.calc_frames([img.ratio for img in row],
                                     stripeWidth, stripeBorder, stripeHeight)
            rows_text = ''.join([utils.render_template(row_temp, img.remote, w, h)
                                 for img, (w, h) in zip(row, dims) if img.is_remote()])
            text += group_temp.replace('{{rows}}', rows_text)

        if utils.text_to_clipboard(text):
            self.show_log(u'Скопировано: {}'.format(len(imglist)))
        else:
            self.show_log(u'Чо та ни фига не могу скопировать')

    def copy_photo_links(self, imglist):
        """
        @type imglist: list of photo.MatchedPhoto
        """
        link_temp = self.user_settings['href_temp']
        text = ''.join([utils.render_template(link_temp, img.remote, 1024, 1024)
                        for img in imglist if img.is_remote()])
        if utils.text_to_clipboard(text):
            self.show_log(u'Скопировано: {}'.format(len(imglist)))
        else:
            self.show_log(u'Чо та ни фига не могу скопировать')

    def create_form(self):
        self.form = overviewfrm.OverviewForm(self, PROGRAM_NAME)
        self.app.SetTopWindow(self.form)
        self.form.Show()

    @utils.http_handler
    def delete_album(self, alb):
        progress = progressctr.Progress(parent=self.form)
        with progress:
            alb.delete(progress)
            self.load_album(alb, progress)
            self.form.UpdateAlbumView(alb)

    def exit(self):
        self.save_user_settings()
        self.save_app_settings()

    def get_user_db_path(self):
        return os.path.join('usr', self.user_name + '.db')

    def get_user_settings_path(self):
        return os.path.join('usr', self.user_name + '.json')

    def init(self):
        self.load_app_settings()
        self.create_form()
        lastuser = self.app_settings.get('lastuser')
        if lastuser:
            self.load_user(lastuser)
        else:
            self.show_name(u'Залогинься!')

    @utils.http_handler
    def load_album(self, alb, progress=None):
        progress = progressctr.Progress.cover(progress, parent=self.form)
        with progress:
            photos = alb.get_photos(progress)
            self.form.ShowPhotos(photos, progress)
            self.show_title(alb)
            self.show_info(u'Всего: {}'.format(len(photos)))
            self.form.SetCurrentAlbum(alb)

    def load_app_settings(self):
        self.app_settings = utils.load_file(SETTINGS_FILE, {})

    @utils.long_time
    @utils.http_handler
    def load_user(self, username, password=None):
        self.form.ClearAll()
        self.user_name = username
        self.user_settings = utils.load_file(self.get_user_settings_path(), DEFAULT_USER_SETTINGS)
        self.user_settings['name'] = self.user_name
        self.app_settings['lastuser'] = self.user_name
        cachedb.connect(self.get_user_db_path())
        auth_token = self.user_settings.get('token')
        if auth_token or password:
            if password:
                yandex_service = yafotki.YandexService(self.user_name, password)
            else:
                yandex_service = yafotki.YandexService(self.user_name, password, auth_token)
            yandex_service.load()
            self.show_name(self.user_name)
            self.load_albums(yandex_service)
        else:
            self.show_name(u'Залогинься!')

    @utils.http_handler
    def load_albums(self, yaservice):
        yaservice.load()
        album_settings = self.user_settings['albums']
        self.user_settings['token'] = yaservice.token
        self.service_album = album.ServiceAlbum(yaservice, album_settings)
        self.form.ShowAlbumTree(self.service_album)

    def login(self):
        dlg = authfrm.AuthDialog(self.form, self.user_name or '', '')
        if dlg.ShowModal() == wx.ID_OK:
            self.load_user(dlg.username, dlg.password)

    def open_photo(self, photos, index=0):
        if not photos or index is None:
            return
        frm = singleviewfrm.SingleviewForm(self.form, photos, index)
        frm.ShowModal()

    @utils.long_time
    def refresh_albums(self):
        self.form.ClearAll()
        yaservice = self.service_album.service
        self.load_albums(yaservice)
        self.form.ReselectAlbum()

    def save_album_settings(self, alb):
        self.user_settings['albums'].update({
            alb.id: alb.get_settings()
        })
        self.save_user_settings()

    def save_app_settings(self):
        utils.save_file(SETTINGS_FILE, self.app_settings)

    def save_user_settings(self):
        if self.user_name:
            utils.save_file(self.get_user_settings_path(), self.user_settings)
        cachedb.close()

    def show_info(self, text):
        self.form.SetStatusText(text, 1)

    def show_log(self, text):
        self.form.SetStatusText(text, 2)

    def show_name(self, text):
        self.form.SetStatusText(text, 0)

    def show_title(self, alb=None):
        title = PROGRAM_NAME
        if alb:
            title += u': ' + alb.title
            if isinstance(alb, album.PhotoAlbum) and alb.folder:
                title += u' - ' + alb.folder
        self.form.SetTitle(title)

    @utils.http_handler
    def upload_album(self, alb):
        progress = progressctr.Progress(parent=self.form)
        with progress:
            alb.synchronize(progress)
            self.load_album(alb, progress)
            self.form.UpdateAlbumView(alb)
